package com.zsr.web.controller.message;

import com.zsr.common.enums.qw.QwTaKeyEnum;
import com.zsr.common.utils.qwchat.WXBizMsgCrypt;
import com.zsr.system.service.qw.IWeChatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.StringReader;

@RestController
@RequestMapping("/wechat")
@Slf4j
public class WeChatMessageController {

    @Resource
    private IWeChatMessageService weChatMessageService;

    @GetMapping("/callback")
    public String verifyCallback(
            @RequestParam("msg_signature") String msgSignature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) throws Exception {

        log.info("接收到消息");
        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(QwTaKeyEnum.TOKEN.getValue(), QwTaKeyEnum.ENCODING_AES_KEY.getValue(), QwTaKeyEnum.CORP_ID.getValue());
        String result = wxBizMsgCrypt.VerifyURL(msgSignature, timestamp, nonce, echostr);
        if (result == null) {
            result = QwTaKeyEnum.TOKEN.getValue();
        }
        log.info("返回结果: {}", result);
        return result;
    }

    @PostMapping("/callback")
    public String handleMessage(HttpServletRequest request,
                                @RequestParam("msg_signature") String msgSignature,
                                @RequestParam("timestamp") String timestamp,
                                @RequestParam("nonce") String nonce) throws Exception {
        log.info("接收到消息，POST");
        log.info("请求信息：{}", request);
        log.info("msg_signature：{}", msgSignature);
        log.info("timestamp：{}", timestamp);
        log.info("nonce：{}", nonce);
        // 读取请求体中的 XML 数据

        StringBuilder xmlData = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                xmlData.append(line);
            }
        }
        log.info("接收到的消息: {}", xmlData);

        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(QwTaKeyEnum.TOKEN.getValue(), QwTaKeyEnum.ENCODING_AES_KEY.getValue(), QwTaKeyEnum.CORP_ID.getValue());
        String sMsg = wxBizMsgCrypt.DecryptMsg(msgSignature, timestamp, nonce, String.valueOf(xmlData));

        log.info("解密后的明文: {}", sMsg);
//        // 解析 XML 数据
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(sMsg));
        Element root = document.getRootElement();

        String toUserName = root.elementText("ToUserName");
        String fromUserName = root.elementText("FromUserName");
        String msgType = root.elementText("MsgType");

        log.info("企业微信CorpID---ToUserName: {}", toUserName);
        log.info("系统生成---FromUserName: {}", fromUserName);
        log.info("消息的类型---MsgType: {}", msgType);

        if ("event".equals(msgType)) {
            // 处理事件消息
            String event = root.elementText("Event"); // 事件类型
            // 客户群事件
            if ("change_external_chat".equals(event)) {
                weChatMessageService.handleChat(root);
            }

            // 标签事件 企微删除标签，不做规则删除，会影响群二维码展示。
            if ("change_external_tag".equals(event)) {
                weChatMessageService.handleTag(root);
            }
        }
        return "success";
    }

}